<?php
namespace Admin\Controller;

use Common\Util\BaseData;
use Common\Util\UserData;
use Services\Vip\VipService;

class AppSettingController extends AdminController{

	public function index(){
		$t_app_setting = M("app_setting");
		$app_config = BaseData::getAppSetting();
		if(IS_AJAX){
			S('app_system_setting_data', null);//清除系统配置缓存
			foreach($_POST as $key => $val){
				if(isset($app_config[$key])){
					$t_app_setting->where("name='$key'")->save(['value' => $val]);
				}else{
					$t_app_setting->add(['name' => $key, 'value' => $val]);
				}
			}
			action_log('更新系统设置', 'AppSetting', 0, $this->c_admin_info['id'], $this->c_admin_info['user_login']);
			$this->return_json_data(1, '配置更新成功');
		}
		if(!empty($app_config['exchang_jifen_config'])){
			$app_config['exchang_jifen_config'] = json_decode($app_config['exchang_jifen_config'], true);
		}
		if(empty($app_config['hexiao_lng'])){
			$app_config['hexiao_lng'] = 116.311478;
		}
		if(empty($app_config['hexiao_lat'])){
			$app_config['hexiao_lat'] = 35.066601;
		}
		$this->assign('info', $app_config);
		$this->meta_title = '系统设置';
		$this->display();
	}

	public function vipSetting(){
		$this->meta_title = 'VIP管理';
		$map = [];
		$list = $this->lists('vip_code', $map, 'id desc', true, 20);
		foreach($list as $key => $val){
			if($val['is_use'] == 1){
				$user_info = UserData::getUserInfoById($val['use_user_id']);
				$list[$key]['user_headimg'] = $user_info['user_headimg'];
				$list[$key]['user_nickname'] = $user_info['user_nickname'];
			}
		}
		$this->assign('list', $list);
		$this->display("vip_list");
	}

	public function addVipSetting(){
		if(IS_AJAX){
			$number = $_POST['number'] ? trim($_POST['number']) : '';
			$vipDay = $_POST['vip_day'] ? intval($_POST['vip_day']) : 0;
            $service = new VipService();
            $result = $service->generateVipCode($number,$vipDay);
			if($result){
				$this->return_json_data(1, '验证码添加成功');
			}else{
				$this->return_json_data(0, '验证码添加失败，请重试');
			}
		}
		$this->meta_title = '添加验证码';
		$this->display("vip_add");
	}

	public function index_edit(){
		$t_vip_setting = M("vip_setting");
		if(IS_POST){
			$id = $_POST['id'] ? $_POST['id'] : '';
			$vip_day = $_POST['vip_day'] ? $_POST['vip_day'] : 0;
			$code = $_POST['code'] ? trim($_POST['code']) : '';
			$s_data['id'] = $id;
			$s_data['code'] = $code;
			$s_data['vip_day'] = $vip_day;
			$s_data['update_time'] = time();
			if($t_vip_setting->save($s_data)){
				$this->success('更新成功');
			}else{
				$this->error('更新失败，请重试');
			}
		}
	}

	public function codeDel(){
		$t_vip_setting = M("vip_setting");
		$id = $_GET['id'];
		if($t_vip_setting->where("id=$id")->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败，请重试');
		}
	}
}
